package com.tydic.baselibrary.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.google.android.material.snackbar.Snackbar;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.tydic.baselibrary.R;
import com.tydic.baselibrary.contant.Constant;
import com.tydic.baselibrary.utils.ToastUtils;
import com.tydic.baselibrary.view.IBaseView;

import java.io.File;
import java.lang.ref.WeakReference;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import cn.jpush.android.api.JPushInterface;


/**
 * 基础Activity
 *
 * @author 依风听雨
 */
public abstract class BaseActivity extends AppCompatActivity implements IBaseView {
    protected SharedPreferences sp;
    protected Handler mHandler = new ActivityHandler(this);
    QMUITipDialog loadingDialog;
    private AlertDialog alertDialog;
    private Toolbar mToolbar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentViewId());
        sp = getSharedPreferences("config", MODE_PRIVATE);
        initToolbar(getToolbarTitle());
        initInstanceState(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        handlerActivity();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ToastUtils.getInstanc(this).destory();
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
            alertDialog = null;
        }
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    /**
     * 处理Activity
     */
    protected abstract void handlerActivity();

    protected void handleMessage(Message msg) {

    }

    /**
     * 获取布局ID
     *
     * @return
     */
    @LayoutRes
    public abstract int getContentViewId();

    /**
     * 初始化ToolBar，需在布局中引入Toolbar布局toolbar_head<br/>
     * Application中设置主题Theme.AppCompat.Light.NoActionBar
     *
     * @param title 　标题
     */
    public void initToolbar(@NonNull String title) {
        mToolbar = findViewById(R.id.toolbar);
        if (mToolbar != null) {
            mToolbar.setTitle(title);
            setSupportActionBar(mToolbar);
        }
    }

    public void setTitle(String title) {
        if (mToolbar != null) {
            mToolbar.setTitle(title);
        }
    }

    public abstract String getToolbarTitle();

    public Toolbar getToolbar() {
        return mToolbar;
    }

    /**
     * 保存状态操作
     *
     * @param savedInstanceState
     */
    protected void initInstanceState(Bundle savedInstanceState) {
    }

    /**
     * 关闭按钮
     */
    protected void disableBackButton() {
        ActionBar ab = getSupportActionBar();
        if (ab != null)
            ab.setDisplayHomeAsUpEnabled(false);
    }

    /**
     * 隐藏键盘
     */
    protected void hideKeyboard() {
        View view = getCurrentFocus();
        if (view != null) {
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
                    hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    protected void showAlertDialog(String title, String message, String positiveText, DialogInterface.OnClickListener listener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(positiveText, listener)
                .setNegativeButton("取消", null);
        alertDialog = builder.show();
    }

    @Override
    public void showProgressDialog() {
        if (loadingDialog == null) {
            loadingDialog = new QMUITipDialog
                    .Builder(this)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                    .setTipWord("正在加载")
                    .create();
        }
        loadingDialog.show();
    }

    @Override
    public void dismissProgressDialog() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    if (loadingDialog != null && loadingDialog.isShowing()) {
                        loadingDialog.dismiss();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 150);
    }

    @Override
    public void showToast(String msg) {
        ToastUtils.getInstanc(this).showToast(msg);
    }

    /**
     * 显示Snackbar
     */
    public void showSnackbar(String msg) {
        if (mToolbar == null) {
            return;
        }
        Snackbar snackbar = Snackbar.make(
                mToolbar,
                msg,
                Snackbar.LENGTH_LONG
        );
        View snackbarView = snackbar.getView();
        TextView snackTextView = snackbarView
                .findViewById(com.google.android.material.R.id.snackbar_text);
        snackTextView.setTextColor(Color.WHITE);
        snackbar.show();
    }

    /**
     * 跳转页面
     *
     * @param clasz
     */
    protected void toPage(Class clasz) {
        toPage(clasz, -1);
    }

    protected void toPage(Class clasz, int requestCode) {
        startActivityForResult(new Intent(this, clasz), requestCode);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                hideKeyboard();
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    /**
     * 判断是否有指定权限
     *
     * @param permissions
     * @return
     */
    public boolean hasPermission(@NonNull String... permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }

        return true;
    }

    /**
     * 申请指定的权限
     *
     * @param requestCode
     * @param permissions
     */
    public void requestPermission(@Constant.PermissionManage int requestCode, @NonNull String... permissions) {
        ActivityCompat.requestPermissions(this, permissions, requestCode);

    }

    /**
     * 更新APP操作
     */
    public void updateApk() {
    }

    /**
     * AndroidO 8.0升级安装Apk
     */
    public void installApk(String filePath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File apkFile = new File(filePath);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri apkUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", apkFile);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");

        }
        startActivity(intent);
    }

    /**
     * 处理获取日历的权限
     */
    public void doCalendarPermission() {
    }

    /**
     * 处理读写SDK的权限
     */
    public void doSDCardPermission() {
    }

    /**
     * 处理获取相机的权限
     */
    public void doCameraPermission() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.INSTALL_APK_CODE) {
            if (Build.VERSION.SDK_INT >= 26) {
                if (getPackageManager().canRequestPackageInstalls()) {
                    updateApk();
                }
            }
        }
    }
//
//    @Override
//    public void onResume() {
//        super.onResume();
//        MobclickAgent.onResume(this);
//    }
//
//    @Override
//    public void onPause() {
//        super.onPause();
//        MobclickAgent.onPause(this);
//    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.WRITE_READ_EXTERNAL_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    doSDCardPermission();
                } else {
                    showToast("您可能已拒绝了应用的读写权限，请在设置里面进行权限配置，谢谢！");
                }
                break;
            case Constant.CALENDAR_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    doCalendarPermission();
                } else {
                    showToast("您可能已拒绝了应用的读写日历权限，请在设置里面进行权限配置，谢谢！");
                }
                break;
            case Constant.CAMERA_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    doCameraPermission();
                } else {
                    showToast("您可能已拒绝了应用的获取相机权限，请在设置里面进行权限配置，谢谢！");
                }
                break;
            case Constant.INSTALL_APK_CODE:
                //AndroidO 8.0升级安装所需权限, 请求安装未知应用来源的权限
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    updateApk();
                } else {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    startActivityForResult(intent, Constant.INSTALL_APK_CODE);
                }
                break;
            default:
                break;
        }
    }

    static class ActivityHandler extends Handler {
        WeakReference<BaseActivity> mActivityReference;

        ActivityHandler(BaseActivity activity) {
            mActivityReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final BaseActivity activity = mActivityReference.get();
            if (activity != null) {
                activity.handleMessage(msg);
            }
        }
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = res.getConfiguration();
        config.fontScale = getSharedPreferences("config", MODE_PRIVATE).getFloat("FONT_SCALE", 1.0f); //设置正常字体大小的倍数
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }
}
